<?php
/** 
 * GETTEXT parser
 *
 * @version 0.2a
 */

 // No direct access
defined( "__DEENZO__" ) or die( "deenzo$" ); 

/* PO parser */
function PO( $gettext ) {

    /* Converting file encoding */
    $po = mb_convert_encoding( file_get_contents( $gettext ), __LC_CTYPE__ );
    
    /** Preformating PO contents */
    $po = preg_split( "/\n\r?/", $po );
    
    unset( $gettext );
    
    foreach ( $po as $e ) {
        if ( ( trim( $e ) != "" ) and !preg_match( "/^\#/", $e ) ) 
            $gettext[] = $e;
    }
    
    $po = preg_replace( "/(msgid|msgstr)/", "@.@\\1", join( "", $gettext ) );
    
    $po = preg_split( "/\@\.\@/", $po ); unset( $gettext );
    
    /* Scanning PO entries */
    foreach ( $po as $e ) {
    
        if ( preg_match( "/^(msgid|msgstr)/", $e ) ) {
            
            /* MSGID register new and continue with next entry */
            if ( preg_match("/^msgid\s/", $e ) ) {
            
                if ( $msgid and ( $msgid != '""' ) ) {
                        
                    $gettext[] = msgid( $msgid, $msgstr, $msgid_plural );
                        
                    unset( $msgid, $msgid_plural, $msgstr );
                
                }
            
                $msgid = preg_replace( "/^msgid\s/", "", $e );
           
            /* Entry is plural */             
            } elseif ( preg_match( "/^msgid_plural\s/", $e ) )
                $msgid_plural = preg_replace( "/^msgid_plural\s/", "", $e ); 
            
            /* MSGSTR is single */
            elseif ( preg_match("/^msgstr\s/", $e ) )
                $msgstr = preg_replace( "/^msgstr\s/", "", $e );
            
            /* MSGSTR is plural */
            elseif ( preg_match( "/^msgstr\[([0-9]+)\]\s/", $e, $d ) )
             $msgstr[ $d[1] ] = preg_replace( "/^msgstr\[([0-9]+)\]\s/", "", $e );
        }
    
    }
    
    // Last GETTEXT entry on file
    $gettext[] = msgid( $msgid, $msgstr, $msgid_plural );
    
    return $gettext;
}

/* Format MSGID-entry */
function msgid( $msgid, $msgstr, $msgid_plural = "" ) {
   
    $e = new stdClass;

    /* MSGID always is present */    
    $e->msgid = preg_replace( array("/^\"/", "/\"$/"), array("", ""), trim( $msgid ) );
    
    /* MSGSTR always is present as single or mutiple-value entry */    
    if ( is_string( $msgstr ) )
        $e->msgstr = preg_replace( array("/^\"/", "/\"$/"), array("", ""), trim( $msgstr ) );
    else {
        foreach ( $msgstr as $k => $v )
            $msgstr[ $k ] = preg_replace( array("/^\"/", "/\"$/"), array("", ""), trim( $msgstr[ $k ] ) );
                
        $e->msgstr = $msgstr;
    }
     
    /* MSGID-plural is present if MSGSTR have multiple values */          
    if ( $msgid_plural )
		$e->msgid_plural = preg_replace( array("/^\"/", "/\"$/"), array("", ""), trim( $msgid_plural ) );
	
	return $e;
}